package com.hzzc.core.service;

import com.hzzc.core.model.SSOResource;
import com.hzzc.core.model.SSORole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * 用户与资源的关系
 */
@Service
public class UserResourceService {

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 资源
     */
    @Autowired
    private ResourceService resourceService;

    /**
     * 角色资源
     */
    @Autowired
    private RoleResourceRelationService roleResourceRelationService;


    /**
     * 获取用户对于单个应用的资源列表
     *
     * @param userId
     * @param appId
     * @return
     */
    public List<SSOResource> getUserAllResourceInThisApp(long userId, Long appId) {
        Set<Long> resourceIds = getUserAllResourceIdsInThisApp(userId, appId);
        if (resourceIds == null || resourceIds.size() == 0) {
            return Collections.emptyList();
        }
        return resourceService.selectByIds(resourceIds);
    }

    /**
     * 获取用户对于单个应用的资源列表
     *
     * @param userId
     * @param appId
     * @return
     */
    public Set<Long> getUserAllResourceIdsInThisApp(long userId, Long appId) {
        List<SSORole> userRoleInThisApp = userRoleService.userRoleInThisApp(userId, appId);
        if (userRoleInThisApp == null || userRoleInThisApp.size() == 0) {
            return Collections.emptySet();
        }
        Set<Long> roleIds = userRoleInThisApp.stream().map(SSORole::getId).collect(Collectors.toSet());
        return roleResourceRelationService.getRoleResourceIds(appId, roleIds);
    }


}
